package com.ht.api.db.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.ht.api.db.Entity;

import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONObject;

/**
 * redis的序列化和反序列化配置
 * @author asq
 * @createTime 2025年1月5日 14:31:44
 */
@Configuration
public class RedisConfig {
	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(factory);

		// 创建 ObjectMapper
		ObjectMapper objectMapper = new ObjectMapper();

		// 配置类型信息
		objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL,
				JsonTypeInfo.As.PROPERTY);

		// 配置其他特性
		objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

		// 为特殊类型添加 MixIn
		objectMapper.addMixIn(Entity.class, EntityMixIn.class);
		objectMapper.addMixIn(JSONObject.class, JSONObjectMixIn.class);
		objectMapper.addMixIn(JSONNull.class, JSONNullMixIn.class);

		// 使用自定义 ObjectMapper 创建序列化器
		GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(objectMapper);

		template.setKeySerializer(new StringRedisSerializer());
		template.setValueSerializer(serializer);
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setHashValueSerializer(serializer);

		template.afterPropertiesSet();
		return template;
	}

	// MixIn 接口定义
	@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
	private abstract class EntityMixIn {
		@JsonCreator
		public EntityMixIn() {
		}
	}

	@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
	private abstract class JSONObjectMixIn {
		@JsonCreator
		public JSONObjectMixIn() {
		}
	}

	@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
	private abstract class JSONNullMixIn {
		@JsonCreator
		public JSONNullMixIn() {
		}
	}
}